<template>
  <view class="login-container">
    <navbar title="登录"/>
    <view class="code-login login-body" v-if="loginType === 'code'">
      <view class="head">
        <view class="title">欢迎来到鼎钻</view>
        <view class="desc">请使用短信验证码登录</view>
      </view>
      <form @submit="codeLogin">
        <view class="form">
          <view class="form-item" style="margin-bottom: 10rpx;">
            <view class="form-label">手机号</view>
            <view class="form-con">
              <input type="number" v-model="codeForm.mobile" placeholder="请输入您的手机号" placeholder-class="place"/>
            </view>
          </view>
          <view class="muted fz-24 mb-32">未注册的手机号将在登录后自动注册</view>
          <view class="form-item">
            <view class="form-label">验证码</view>
            <view class="form-con code-item">
              <input type="text" v-model="codeForm.captcha" placeholder="请输入短信验证码" placeholder-class="place"/>
              <button class="code-btn"
                      :class="{muted: timeDown != 60}"
                      hover-class="none"
                      @click="getCaptcha">
                {{ timeDown == 60 ? '获取验证码' : `${timeDown}s后后重试` }}
              </button>
            </view>
          </view>
        </view>
        <button form-type="submit" hover-class="none" class="btn-login" @click="codeLogin">登录</button>
        <view class="handler">
          <view @click="loginType = 'password'">
            <text class="iconfont icon-password"/>
            密码登录
          </view>
          <button open-type="getPhoneNumber" hover-class="none">
            <text class="iconfont icon-phone"/>
            快捷登录
          </button>
        </view>
      </form>
    </view>
    <view class="code-login login-body" v-else-if="loginType === 'password'">
      <view class="head">
        <view class="title">欢迎来到鼎钻</view>
        <view class="desc">请使用密码登录</view>
      </view>
      <form @submit="pwdLogin">
        <view class="form">
          <view class="form-item">
            <view class="form-label">账号</view>
            <view class="form-con">
              <input type="number" v-model="pwdForm.username" placeholder="请输入您的账号" placeholder-class="place"/>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">密码</view>
            <view class="form-con code-item">
              <input type="password" v-model="pwdForm.password" placeholder="请输入密码" placeholder-class="place"/>
            </view>
          </view>
        </view>
        <button form-type="submit" hover-class="none" class="btn-login">登录</button>
        <view class="handler">
          <view @click="loginType = 'code'">
            <text class="iconfont icon-yzm"/>
            验证码登录
          </view>
          <button open-type="getPhoneNumber" hover-class="none" @getphonenumber="getPhoneNumber">
            <text class="iconfont icon-phone"/>
            快捷登录
          </button>
        </view>
      </form>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <ws-wx-privacy ref="privacyPopup" id="privacy-popup"/>
    <!-- #endif -->
  </view>
</template>

<script>
import {getPhone, getSessionKey, miniPhoneLogin, sendSms, submitLogin, wxLogin} from '@/api/login';
import {mapActions} from 'vuex';

export default {
  data() {
    return {
      redirect: '',
      loginType: 'password',
      timeDown: 60,
      codeForm: {
        mobile: '',
        captcha: '',
        smsmode: 2,
      },
      codeRules: {
        mobile: [
          {required: true, message: '请输入手机号'},
          {phone: true, message: '请输入正确的手机号'}
        ],
        captcha: [
          {required: true, message: '请输入验证码'},
        ]
      },
      pwdForm: {
        username: '',
        password: ''
      },
      pwdRules: {
        username: [
          {required: true, message: '请输入账号'},
        ],
        password: [
          {required: true, message: '请输入密码'},
        ],
        openid: [
          {required: true, message: '微信授权失败'}
        ]
      },
      showBind: false,
      editModal: false,
      wxInfo: {}
    };
  },
  methods: {
    ...mapActions(['login']),
    pwdLogin() {
      this.pwdForm.needCaptcha = false
      this.$verify.verifyForm(this.pwdForm, this.pwdRules).then(() => {
        uni.showLoading({
          title: '登录中'
        })
        submitLogin(this.pwdForm).then(res => {
          this.login(res)
          this.$toast('登录成功', () => {
            if (this.redirect) {
              uni.redirectTo({
                url: decodeURIComponent(this.redirect)
              })
              return
            }
            uni.switchTab({url: '/pages/index/index'})
          })
        })
      })
    },
    getWxLogin() {
      uni.login({
        success: ({code}) => {
          getSessionKey({code}).then(res => {
            this.wxInfo = res
            this.codeForm.openid = res.openid
          })
        }
      })
    },
    getPhoneNumber(e) {
      console.log(e)
      if (e.detail.errMsg.indexOf('getPhoneNumber:fail') > -1) {
        this.$toast('获取手机号失败')
        return
      }
      uni.login({
        success: ({code}) => {
          uni.showLoading({
            title: '登录中'
          })
          getSessionKey({code}).then(({sessionId, openid}) => {
            getPhone({
              code: e.detail.code,
              sessionId: sessionId,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            }).then(res => {
              wxLogin({
                phone: res.phoneNumber,
                openid: openid
              }).then(res1 => {
                this.login(res1.result)
                this.$toast('登录成功', () => {
                  if (this.redirect) {
                    uni.redirectTo({
                      url: decodeURIComponent(this.redirect)
                    })
                    return
                  }
                  uni.switchTab({url: '/pages/index/index'})
                })
              })
            })
          })
        }
      })
    },
    getCaptcha() {
      if (this.timeDown != 60) return
      if (!this.codeForm.mobile) {
        this.$toast('请输入手机号')
        return
      }
      uni.showLoading({mask: true})
      sendSms(this.codeForm).then(res => {
        this.$toast('验证码已发送')
        let timer = setInterval(() => {
          this.timeDown--
          if (this.timeDown == 0) {
            clearInterval(timer)
            this.timeDown = 60
          }
        }, 1000)
      })
    },
    codeLogin() {
      this.$verify.verifyForm(this.codeForm, this.codeRules).then(() => {
        uni.showLoading({
          title: '登录中'
        })
        miniPhoneLogin(this.codeForm).then(res => {
          this.login(res)
          this.$toast('登录成功', () => {
            if (this.redirect) {
              uni.redirectTo({
                url: decodeURIComponent(this.redirect)
              })
              return
            }
            uni.switchTab({url: '/pages/index/index'})
          })
        })
      })
    }
  },
  onLoad(options) {
    this.redirect = options.redirect
  },
  onShow() {
    this.getWxLogin()
  }
}
</script>

<style lang="scss">
@import '@/static/styles/minix.scss';

page {
  background: #fff;
}

.login-body {
  padding: 120rpx 30rpx 0;

  .head {
    .title {
      font-size: 48rpx;
    }

    .desc {
      font-size: 24rpx;
      color: $-color-muted;
    }
  }

  .form {
    margin-top: 60rpx;

    .form-item {
      margin-bottom: 32rpx;
      flex-direction: column;
      height: auto;
      line-height: inherit;

      .form-item {
        font-size: 32rpx;
      }

      .form-con {
        border: 1rpx solid #e6e6e6;
        height: 80rpx;
        display: flex;
        align-items: center;
        border-radius: 16rpx;
        padding: 0 20rpx;
        margin-top: 20rpx;

        input {
          flex: 1;
        }

        .code-btn {
          margin-left: 20rpx;
          font-size: 24rpx;
          color: $-color-gray;
        }
      }
    }

  }

  .btn-login {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    color: #fff;
    background: #000;
    border-radius: 16rpx;
    margin-top: 70rpx;

    &[disabled] {
      background: #ccc;
    }
  }

  .handler {
    @include flex-between;
    margin-top: 28rpx;

    button {
      padding: 0;
      margin: 0;
      line-height: inherit;
    }

    view, button {
      padding: 0 26rpx;
      line-height: 55rpx;
      text-align: center;
      border-radius: 40rpx;
      border: 1px solid #e6e6e6;
    }

    .iconfont {
      font-size: 34rpx;
      vertical-align: -2rpx;
    }
  }
}
</style>
